from google.appengine.api import users
import settings
import jinja2
import os
import logging

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=["jinja2.ext.do", "jinja2.ext.autoescape"])


def login_required(handler_method):
    '''
    Very simple handler method decorator for ensuring the user is logged in.

    :param handler_method:
    :return:
    '''
    def check_login(self, *args, **kwargs):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.url))
        elif user.email().lower() in settings.ADMIN_USERS:
            handler_method(self, *args, **kwargs)
        else:
            self.redirect(users.create_logout_url("/"))
    return check_login

def admin_user(handler_method):
    '''
    handler method decorator for ensuring the user is admin.

    :param handler_method:
    :return:
    '''
    def check_admin(self, *args, **kwargs):
        user = users.get_current_user()
        email = user.email()
        if email not in settings.ADMIN_USERS:
            template = jinja_environment.get_template('templates/front_page.html')
            self.response.out.write(template.render())
        else:
            handler_method(self, *args, **kwargs)
    return check_admin